共计 1975 个字符,预计需要花费 5 分钟才能阅读完成。
前言
WordPress 开启 CDN 静态缓存页面之后,当我们访问文章的时候,便不会去请求源站,而是返回 CDN 缓存了的页面,所以文章的浏览数量不会进行自增以及其他的变化。
解决办法
首先,我们在网站的根目录新建一个操作文件,命名为views.php
,将以下代码写入此文件中。
<?php require('wp-blog-header.php'); ?>
<?php
$ajaxHead = $_SERVER['HTTP_X_REQUESTED_WITH'];
if(strtoupper($ajaxHead)==strtoupper("XMLHttpRequest")) {$post_id = $_POST['post_id'];
echo $post_id;
$sql = "update `wp_postmeta` set `meta_value`=`meta_value`+1 where `post_id`='${post_id}'AND `meta_key`='views';";
$wpdb->query($sql);
}else{header("HTTP/2 404 Not Found");
header("Status: 404 Not Found");
exit;
}
<?php
/**
* @author Licoy.cn
* @version 2017/8/8
*/
require('../../wp-blog-header.php');
$isXhr = $_SERVER['HTTP_X_REQUESTED_WITH'];
if (strtoupper($isXhr) == strtoupper("XMLHttpRequest")) {$post_id = $_POST['post_id'];
$po = get_post_meta($post_id,'views',true);
if(!$po) {
// 表示不存在这个自定义栏目,那么新增这个自定义栏目
add_post_meta($post_id, 'views', 1, true);
echo 1;
} else {
// 若已存在这个自定义栏目,则先获取当前数值,并递增 +1,再更新数据库
$count = $po + 1;
update_post_meta($post_id,'views',$count);
echo $count;
}
} else {header("Status: 403 Not Found");
exit;
}
接着我们在主题的 page.php 文件中插入以下代码:
$(function(){function page_views() {if(!window.localStorage) {console.info('浏览器不支持 localStorage');
}else{var post_id = <?php the_ID();?>;
var views = localStorage.getItem("view_list");
if(views===null){localStorage.setItem("view_list",post_id);
$.post("/views.php?time="+new Date().getTime(),{post_id:post_id});
return true;
}else{var item = views.split("|");
var bool = $.inArray(post_id+'',item);
if(bool===-1){$.post("/views.php?time="+new Date().getTime(),{post_id:post_id});
localStorage.setItem("view_list",views+"|"+post_id);
return true;
}
return false;
}
}
}
page_views();});

